//
//  MBDetailViewController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/10/6.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBDetailViewController.h"
#import "MBSpaceNewsDetailCell.h"
#import "MBSpaceNewsDetailViewController.h"
#import "MBLoginController.h"
#import "AppDelegate.h"
#import <MediaPlayer/MediaPlayer.h>

#import "EmojiView.h"
#import "MBBottomView.h"
#import "Music.h"

@interface MBDetailViewController ()<UITableViewDelegate,UITableViewDataSource,MBBottomViewDelegate,MBSpaceNewsDetailCellDelegate,UITextFieldDelegate,UIScrollViewDelegate,EmojiViewDelegate>{
    UIView                              *_scrollView;
    UIImageView                         *_userImgView;
    UILabel                             *_nickNameLb;
    UILabel                             *_timeLb;
    UILabel                             *_contentLb;
    UILabel                             *_fansLb;
    UIButton                            *_focusBtn;
    UILabel                              *_listenCount;
    CLShareManager *shareView;
    MBBottomView   *_bottomView;
    UIButton                            *downloadBt;
    UIView                              *noLrcView;
    UIImageView                         *_bgImgView;
    UIButton                            *singleBtn;
    UIButton                            *playBt;
    UILabel                             *titleBgLb;
    UITableView                         *_tableView;
    UIImageView                         *listenImgView;
    NSMutableArray                      *_mutArr;       //评论信息
    NSMutableArray                      *_mutHeightArr; //评论信息高度
    NSString                            *_commentNum;  //评论条数
    NSString                            *fansNum;       //粉丝数
    NSString                            *statusStr;     //是否关注
    UISlider                            *slide;
    UIView                              *_inputView;
    UITextField                         *_inputField;
    UIView                              *_showderView;
    UIButton                            *sureBt;
    float                               inputTime;
    NSMutableDictionary                 *_replyMutDic;  //当前评论
    BOOL                                isZheDang;
    
    AVPlayer                            *audioPlayer;
    NSMutableArray                      *musicArray;    //歌词列表
    NSInteger                           musicArrayNumber;//播放当前条音频
    BOOL                                isCircle;       //是否自动播放
    BOOL                                isPlay;         //是否播放
    NSMutableArray                      *collectionMusicArr; //收藏
    Music                               *currentMusic; //当前music
    NSMutableArray                      *fileIDArr;     //下载方便
    PLayerModelType                     playModelType; //播放模式
    NSTimer                             *_showTimer;
    NSArray                             *downedMusicArr;//已下载的歌曲
    NSMutableArray                      *_praiseListArr;   //点赞数量
    int                                 nextPlay;
    AVAudioSession                      *_audioSession;
    UIButton                            *deleteBtn;
    UIView                              *_navBgView;
    UIButton                            *emojiBt;
    EmojiView                           *_emojiView;
}

@end

@implementation MBDetailViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    isZheDang = NO;
    [self registerForKeyboardNotifications];
    [self onLoadData];
    
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    //离开判断播放器是否正在播放
    [[UserManager standerDefult] setMainPlayer:audioPlayer];
    [[UserManager standerDefult]setIsBackPlay:isPlay];
    [[UserManager standerDefult]setMainPoint:CGPointMake(0, 0)];
    
    [[UserManager standerDefult]setSelectMusicIndex:musicArrayNumber];
    [[UserManager standerDefult]setMusicArr:musicArray];
    [[UserManager standerDefult]setQinzixiuArr:_dataAllArr];
    [[UserManager standerDefult]setIsPlaying:isPlay];
    [[UserManager standerDefult]setIsLastID:[NSString stringWithFormat:@"%@",currentMusic.ID]];
    [[UserManager standerDefult]setMusicPlayType:MusicPLayType_Collection];
    
    if (_showTimer) {
        [_showTimer invalidate];
        _showTimer = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
    
    [self removeForKeyboardNotifications];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    shareView = [[CLShareManager alloc] init];
    _mutArr = [[NSMutableArray alloc]init];
    _replyMutDic = [[NSMutableDictionary alloc]init];
    isPlay = YES;            //是否处于播放状态
    isCircle = YES;          //判断是否允许循环播放
    musicArrayNumber = 0;    //歌曲列表中第几条
    collectionMusicArr = [[NSMutableArray alloc]init];                             //收藏
    nextPlay = 1;
    downedMusicArr = [[NSMutableArray alloc]init];
    _praiseListArr = [[NSMutableArray alloc]init];
    _dateDic = [[NSMutableDictionary alloc]init];
    _mutHeightArr = [[NSMutableArray alloc]init];
    
    [self onCreateUI];
    [self setNavBar];

    [self initDate];
    
    [self onCreateUIForAudio];
}

#pragma mark - UI
- (void)setNavBar {
    //导航
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    bgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgView];
    [self.view bringSubviewToFront:bgView];
    _navBgView = bgView;
    
    UIImage *img = [UIImage imageNamed:@"fanhui"];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(10, 20+(44-img.size.height)/2, 80, img.size.height);
    [back setImage:img forState:UIControlStateNormal];
    [back setImage:img forState:UIControlStateHighlighted];
    [back setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80-img.size.width)];
    [back addTarget:self action:@selector(onBack ) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:back];
    
    titleBgLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 20+7, SCREEN_WIDTH, 30)];
    titleBgLb.textAlignment = NSTextAlignmentCenter;
    titleBgLb.textColor = [UIColor whiteColor];
    [bgView addSubview:titleBgLb];
    
    deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(SCREEN_WIDTH-85, titleBgLb.top, 80, 30);
    [deleteBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
    [deleteBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateHighlighted];
    deleteBtn.backgroundColor = [UIColor clearColor];
    [deleteBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 40, 0, 0)];
    [deleteBtn addTarget:self action:@selector(onDeleteMusicAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:deleteBtn];
}

- (void)onCreateUI {

    _scrollView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT)];
    _scrollView.backgroundColor = [UIColor clearColor];

    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 740*PERCEN)];
    bgView.backgroundColor = [[UIColor lightGrayColor]colorWithAlphaComponent:.35];
    [_scrollView addSubview:bgView];
    //背景图
    _bgImgView = [[UIImageView alloc] initWithFrame:bgView.bounds];
    [bgView addSubview:_bgImgView];
    //不透明底部
    UIView *alphaBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, bgView.height-140*PERCEN, bgView.width, 140*PERCEN)];
    alphaBottomView.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.6];
    [_scrollView addSubview:alphaBottomView];
    //单曲循环
    UIImage *single = [UIImage imageNamed:@"danqu"];
    NSString *qinzinxiuType = [[NSUserDefaults standardUserDefaults]objectForKey:@"qinzixiu_play_Type"];
    switch ([qinzinxiuType intValue]) {
        case 1:
        {
            single = [UIImage imageNamed:@"shunxu"];
            playModelType = PLayerModelType_Shunxu;
        }
            break;
        case 2:
        {
            single = [UIImage imageNamed:@"suiji"];
            playModelType = PLayerModelType_SuiJi;
        }
            break;
        case 3:
        {
            single = [UIImage imageNamed:@"danqu"];
            playModelType = PLayerModelType_DanQu;
        }
            break;
            
        default:
            break;
    }

    singleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    singleBtn.backgroundColor = [UIColor clearColor];
    singleBtn.frame = CGRectMake(45*PERCEN, (alphaBottomView.height-single.size.height)/2, 60*PERCEN, 60*PERCEN);
    [singleBtn setImage:single forState:UIControlStateNormal];
    [singleBtn setImage:single forState:UIControlStateHighlighted];
    [singleBtn addTarget:self action:@selector(singleCircle) forControlEvents:UIControlEventTouchUpInside];
    [alphaBottomView addSubview:singleBtn];
    //上一首
    UIImage *lastImg = [UIImage imageNamed:@"shangyiqu"];
    UIButton *lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lastBtn.frame = CGRectMake(singleBtn.right+80*PERCEN, (alphaBottomView.height-lastImg.size.height)/2, 80*PERCEN, 80*PERCEN);
    lastBtn.backgroundColor = [UIColor clearColor];
    [lastBtn setImage:lastImg forState:UIControlStateNormal];
    [lastBtn setImage:lastImg forState:UIControlStateHighlighted];
    [lastBtn addTarget:self action:@selector(onSelectLastPlaying) forControlEvents:UIControlEventTouchUpInside];
    [alphaBottomView addSubview:lastBtn];

    //播放、暂停
    UIImage *playImg = [UIImage imageNamed:@"bofang_xbtj"];
    UIImage *playingImg = [UIImage imageNamed:@"zanting_xbtj"];
    playBt = [UIButton buttonWithType:UIButtonTypeCustom];
    playBt.backgroundColor = [UIColor clearColor];
    playBt.frame = CGRectMake(lastBtn.right+60*PERCEN, (alphaBottomView.height-playImg.size.height)/2., 100*PERCEN, 100*PERCEN);
    [playBt setImage:playImg forState:UIControlStateNormal];
    [playBt setImage:playingImg forState:UIControlStateSelected];
    [playBt addTarget:self action:@selector(onSelectPlayedType:) forControlEvents:UIControlEventTouchUpInside];
    [alphaBottomView addSubview:playBt];
    //下一个
    UIImage *nextImg = [UIImage imageNamed:@"xiayiqu"];
    UIButton *nextBt = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBt.backgroundColor = [UIColor clearColor];
    nextBt.frame = CGRectMake(playBt.right+60*PERCEN, (alphaBottomView.height-nextImg.size.height)/2., 80*PERCEN, 80*PERCEN);
    [nextBt setImage:nextImg forState:UIControlStateNormal];
    [nextBt setImage:nextImg forState:UIControlStateHighlighted];
    [nextBt addTarget:self action:@selector(onSelectNextPlaying) forControlEvents:UIControlEventTouchUpInside];
    [alphaBottomView addSubview:nextBt];
    //下载
    UIImage *downloadImg = [UIImage imageNamed:@"weixiazai"];
    UIImage *downedLoadImg = [UIImage imageNamed:@"yixiazai"];
    UIImage *downedLoadingImg = [UIImage imageNamed:@"xiazaizhong"];
    downloadBt = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadBt.backgroundColor = [UIColor clearColor];
    downloadBt.frame = CGRectMake(nextBt.right+80*PERCEN, (alphaBottomView.height-downloadImg.size.height)/2., 60*PERCEN, 60*PERCEN);
    [downloadBt setImage:downloadImg forState:UIControlStateNormal];
    [downloadBt setImage:downedLoadImg forState:UIControlStateSelected];
    [downloadBt setImage:downedLoadingImg forState:UIControlStateDisabled];
    [downloadBt addTarget:self action:@selector(onSelectdownload) forControlEvents:UIControlEventTouchUpInside];
    [alphaBottomView addSubview:downloadBt];

    //进度条
    slide = [[UISlider alloc]initWithFrame:CGRectMake(0, alphaBottomView.height-4, alphaBottomView.width, 2)];
//    slide.backgroundColor = [UIColor colorWithRed:193/255. green:193/255. blue:193/255. alpha:1.];
    slide.minimumValue = 0;
    slide.maximumValue = 1;
    slide.value = 0;
    slide.minimumTrackTintColor = TINK_BG_COLOR;
    slide.maximumTrackTintColor = [UIColor colorWithRed:193/255. green:193/255. blue:193/255. alpha:1.];
    [slide setThumbImage:[UIImage imageNamed:@"jiedian"] forState:UIControlStateNormal];
    [slide setThumbImage:[UIImage imageNamed:@"jiedian"] forState:UIControlStateHighlighted];
//    [slide setTranslatesAutoresizingMaskIntoConstraints:NO];
    [alphaBottomView addSubview:slide];
    [slide addTarget:self action:@selector(onChangeSlide) forControlEvents:UIControlEventValueChanged];

    //2.信息
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, bgView.bottom+1, SCREEN_WIDTH, 87)];
    bottomView.backgroundColor = [UIColor whiteColor];
    
    [_scrollView addSubview:bottomView];
    
    //头像
    _userImgView = [[UIImageView alloc]initWithFrame:CGRectMake(25*PERCEN, 30*PERCEN, 80*PERCEN, 80*PERCEN)];
    _userImgView.backgroundColor = [UIColor clearColor];
    _userImgView.layer.cornerRadius = _userImgView.height / 2.;
    _userImgView.layer.masksToBounds = YES;
    [bottomView addSubview:_userImgView];
    
    _nickNameLb = [[UILabel alloc]initWithFrame:CGRectMake(_userImgView.right+20*PERCEN, _userImgView.top, 200, 20)];
    _nickNameLb.backgroundColor = [UIColor clearColor];
    _nickNameLb.textAlignment = NSTextAlignmentLeft;
    _nickNameLb.textColor = UIColorFromHex(0x333333);
    _nickNameLb.font = [UIFont systemFontOfSize:13.f];
    [bottomView addSubview:_nickNameLb];
    
    _fansLb = [[UILabel alloc] initWithFrame:CGRectMake(_userImgView.right+20*PERCEN, _nickNameLb.bottom, 200, 20)];
    _fansLb.backgroundColor = [UIColor clearColor];
    _fansLb.textAlignment = NSTextAlignmentLeft;
    _fansLb.textColor = UIColorFromHex(0x999999);
    _fansLb.font = [UIFont systemFontOfSize:12.f];
    [bottomView addSubview:_fansLb];
    
    UIImage *timeImg = [UIImage imageNamed:@"shijian_qzxbf"];
    UIImageView *timeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(25*PERCEN, _userImgView.bottom+20*PERCEN, timeImg.size.width, timeImg.size.height)];
    timeImgView.backgroundColor = [UIColor clearColor];
    timeImgView.layer.cornerRadius = timeImgView.height / 2.;
    timeImgView.layer.masksToBounds = YES;
    timeImgView.image = timeImg;
    [bottomView addSubview:timeImgView];
    
    _timeLb = [[UILabel alloc]initWithFrame:CGRectMake(timeImgView.right+10*PERCEN,  _userImgView.bottom+20*PERCEN, 100, timeImg.size.height)];
    _timeLb.backgroundColor = [UIColor clearColor];
    _timeLb.textAlignment = NSTextAlignmentLeft;
    _timeLb.textColor = UIColorFromHex(0x999999);
    _timeLb.font = [UIFont systemFontOfSize:12.f];
    [bottomView addSubview:_timeLb];
    UIImage *focusImg = [UIImage imageNamed:@"yiguanzhu_fs"];
    UIImage *focuImg = [UIImage imageNamed:@"jiaguanzhu_fs"];
    _focusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _focusBtn.frame = CGRectMake(SCREEN_WIDTH-focusImg.size.width-25*PERCEN, 30*PERCEN, focusImg.size.width, focusImg.size.height);
    [_focusBtn setImage:focuImg forState:UIControlStateNormal];
    [_focusBtn setImage:focusImg forState:UIControlStateSelected];
    _focusBtn.backgroundColor = [UIColor clearColor];
    [_focusBtn addTarget:self action:@selector(focusClick:) forControlEvents:UIControlEventTouchUpInside];
    _focusBtn.hidden = NO;
    if (_dateDic) {
        if ([UserManager standerDefult].userModel) {
            if ([[_dateDic objectForKey:@"UserID"]intValue] == [[UserManager standerDefult].userModel.UserID intValue]) {
                _focusBtn.hidden = YES;
            }
        }
    }
    [bottomView addSubview:_focusBtn];
    
    _listenCount = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-25*PERCEN-100, _timeLb.top, 100, timeImg.size.height)];
    _listenCount.backgroundColor = [UIColor clearColor];
    _listenCount.textAlignment = NSTextAlignmentRight;
    _listenCount.textColor  = UIColorFromHex(0x999999);
    _listenCount.font = [UIFont systemFontOfSize:12.f];
    [bottomView addSubview:_listenCount];
    UIImage *listenImg = [UIImage imageNamed:@"shiting_qzxbf"];
    listenImgView = [[UIImageView alloc] initWithFrame:CGRectMake(_listenCount.left-10*PERCEN-listenImg.size.width, _listenCount.top, listenImg.size.width, listenImg.size.height)];
    listenImgView.backgroundColor = [UIColor clearColor];
    listenImgView.layer.cornerRadius = timeImgView.height / 2.;
    listenImgView.layer.masksToBounds = YES;
    listenImgView.image = listenImg;
    [bottomView addSubview:listenImgView];
    _scrollView.height = bottomView.bottom;
    
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-50) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = _scrollView;
    _tableView.tableFooterView = [self getTableFooterView];
    
    //键盘
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
    _inputView.backgroundColor = UIColorFromHex(0xf5f5f5);
    _inputView.hidden = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_inputView];
    
    emojiBt = [UIButton buttonWithType:UIButtonTypeCustom];
    emojiBt.backgroundColor = [UIColor clearColor];
    emojiBt.frame = CGRectMake(0, 0, 50, _inputView.height);
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
    [emojiBt setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
    [emojiBt addTarget:self action:@selector(onSelectEmojiAction:) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:emojiBt];
    
    _inputField = [[UITextField alloc]initWithFrame:CGRectMake(50, 5, _inputView.width-50-50, 30)];
    _inputField.backgroundColor = [UIColor whiteColor];
    _inputField.placeholder = @"填写评论";
    _inputField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputField.delegate = self;
    [_inputField setValue:[UIFont systemFontOfSize:13]forKeyPath:@"_placeholderLabel.font"];
    _inputField.font = [UIFont systemFontOfSize:13];
    [_inputField resignFirstResponder];
    [_inputView addSubview:_inputField];
    
    sureBt = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBt.backgroundColor = [UIColor clearColor];
    sureBt.frame = CGRectMake(_inputView.width - 50, 0, 50, _inputView.height);
    [sureBt setTitle:@"发送" forState:UIControlStateNormal];
    [sureBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    sureBt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [sureBt addTarget:self action:@selector(onSelectSureAction) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:sureBt];
    
    _showderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 216 - 40)];
    _showderView.backgroundColor = [UIColorFromHex(0x000000) colorWithAlphaComponent:.2];
    _showderView.hidden = YES;
    _showderView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:_showderView];
    
    //表情
    _emojiView = [[EmojiView alloc]init];
    _emojiView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_emojiView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapHideInputAction)];
    [_showderView addGestureRecognizer:tap];
    
    [self.view addSubview:[self setUpBottomView]];

    [self addNoGeCi];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieToFaile:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
}

- (UIView *)getTableFooterView
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.userInteractionEnabled = YES;
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 10*PERCEN, SCREEN_WIDTH, 80*PERCEN)];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.userInteractionEnabled = YES;
    [bgView addSubview:contentView];
    
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
    bt.frame = CGRectMake((contentView.width-100)/2 , 0, 100, contentView.height);
    bt.backgroundColor = [UIColor clearColor];
    [bt setTitle:@"查看所有评论 >>" forState:UIControlStateNormal];
    [bt setTitle:@"查看所有评论 >>" forState:UIControlStateHighlighted];
    [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
    [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateHighlighted];
    bt.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [bt addTarget:self action:@selector(onSelectForNewCellAction) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:bt];
    
    return bgView;
}

- (void)addNoGeCi
{
    //无歌曲
    noLrcView = [[UIView alloc]initWithFrame:_bgImgView.bounds];
    noLrcView.backgroundColor = [UIColor clearColor];
    [_bgImgView addSubview:noLrcView];
    noLrcView.hidden = YES;
    
    UIImage *img = [UIImage imageNamed:@"zanwugeci"];
    UIImageView *imgLrcView = [[UIImageView alloc]initWithFrame:CGRectMake((noLrcView.width-img.size.width)/2., ((noLrcView.height - img.size.height - 20)/2.), img.size.width, img.size.height)];
    imgLrcView.image = img;
    imgLrcView.backgroundColor = [UIColor clearColor];
    [noLrcView addSubview:imgLrcView];
    
    UILabel *noLrcLb = [[UILabel alloc]initWithFrame:CGRectMake(0, imgLrcView.bottom+20, noLrcView.width, 20)];
    noLrcLb.text =@"暂无歌词";
    noLrcLb.textAlignment = NSTextAlignmentCenter;
    noLrcLb.textColor = [UIColor whiteColor];
    noLrcLb.font = [UIFont systemFontOfSize:14.f];
    [noLrcView addSubview:noLrcLb];
}

- (MBBottomView *)setUpBottomView
{
    if (!_bottomView) {
        _bottomView =[[MBBottomView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-50, SCREEN_WIDTH, 50)];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

- (NSMutableArray *)dataAllArr
{
    if (!_dataAllArr) {
        _dataAllArr = [[NSMutableArray alloc]init];
    }
    return _dataAllArr;
}

- (void)onCreateUIForAudio
{
    if (!_audioSession) {
        _audioSession = [AVAudioSession sharedInstance];
    }
    [_audioSession setActive:YES error:nil];
    [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    if ([UserManager standerDefult].mainPlayer) {
        if ([UserManager standerDefult].isPlaying) {
            _showTimer =[NSTimer scheduledTimerWithTimeInterval:0.1f
                                                         target:self
                                                       selector:@selector(showTime)
                                                       userInfo:nil
                                                        repeats:YES];
        }
        audioPlayer = [UserManager standerDefult].mainPlayer;
        [[UserManager standerDefult] setIsBackPlay:NO];
        
        if (![self.selectMusicID isEqualToString:[NSString stringWithFormat:@"%@",currentMusic.ID]]) {
             NSURL *urlPath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",currentMusic.urlPath]];
            [audioPlayer replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:urlPath]];
        }
        
    } else {
        NSURL *urlPath;
        urlPath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",currentMusic.urlPath]];
        
        AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
        audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];

    }
    titleBgLb.text = currentMusic.name;
    [self onSelectPlayedType:playBt];
}

#pragma mark - 加载数据
- (void)onLoadData
{
    [_dateDic removeAllObjects];
    NSInteger selectIndex = [[UserManager standerDefult]selectMusicIndex];
    if (selectIndex < _dataAllArr.count) {
        [_dateDic addEntriesFromDictionary:[_dataAllArr objectAtIndex:selectIndex]];
    } else {
        return;
    }
    
    //分享
    _bottomView.shareNum = [NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"ShareNum"]];
    //下载
    //已下载亲子秀记录
    downedMusicArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
    fileIDArr = [[NSMutableArray alloc]initWithCapacity:downedMusicArr.count];
    for (int i=0; i<downedMusicArr.count; i++) {
        NSDictionary *dic = [downedMusicArr objectAtIndex:i];
        NSString *fileID = [dic objectForKey:@"musicId"];
        [fileIDArr addObject:fileID];
    }
    NSString *currentId = [NSString stringWithFormat:@"%@",currentMusic.ID];
    BOOL isDowned = NO;
    for (NSDictionary *dic in downedMusicArr) {
        NSString *idString = [dic objectForKey:@"musicId"];
        if ([idString isEqualToString:currentId]) {
            isDowned = YES;
        }
    }
    
    if (isDowned == YES) {
        downloadBt.selected = YES;
    } else {
        //未已下载好 判断是否正在下载
        NSMutableArray *mMusicArr = [[NSMutableArray alloc]init];
        [mMusicArr addObjectsFromArray:[UserManager standerDefult].downingMusicCountArr];
        [mMusicArr addObjectsFromArray:[UserManager standerDefult].waitDownMusicCountArr];
        if (mMusicArr.count > 0) {
            for (DownMusicModel *model in mMusicArr) {
                if ([model.musicID intValue] == [currentMusic.ID intValue] && [model.musicType intValue] == [currentMusic.musicType intValue]) {
                    downloadBt.selected = YES;
                    downloadBt.enabled = NO;
                } else {
                    downloadBt.selected = NO;
                    downloadBt.enabled = YES;
                }
            }
        } else {
            downloadBt.selected = NO;
            downloadBt.enabled = YES;
        }
    }
    
    if (_dateDic && _focusBtn) {
        if ([UserManager standerDefult].userModel) {
            if ([[_dateDic objectForKey:@"UserID"]intValue] == [[UserManager standerDefult].userModel.UserID intValue]) {
                _focusBtn.hidden = YES;
            }
        }
    }
    
    //列入最近播放
    if (currentMusic.ID) {
        FMManageObject *manager = [FMManageObject standerDefault];
        NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",currentMusic.ID]];
        if (arrs.count == 0) {
            //来吧
            [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:currentMusic.name withFileID:currentMusic.ID withUrl:currentMusic.urlPath withSize:currentMusic.Capacity withType:[NSString stringWithFormat:@"%@",currentMusic.musicType] withCoverPath:[NSString stringWithFormat:@"%@",currentMusic.CoverPath] withDate:[[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"CreateTime"]] getChaTime] withSentiment:[NSString stringWithFormat:@"%@",currentMusic.Sentiment] withTitle:[NSString stringWithFormat:@"%@",currentMusic.name] withUserId:[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"UserID"]] withUserPic:[_dateDic objectForKey:@"FaceImg"] withUserNick:[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"NickName"]]];
        }
    }
    
    UserModel *model = [UserManager standerDefult].userModel;
    //删除按钮是否隐藏
    deleteBtn.hidden = YES;
    if (_dateDic.allKeys.count > 0) {
        if ([_dateDic.allKeys containsObject:@"UserID"]) {
            if ([[_dateDic objectForKey:@"UserID"]intValue] == [model.UserID intValue]) {
                //相同
                deleteBtn.hidden = NO;
            }
        }
    }
    
    //评论接口
    [self onShowCommentData:model];
    
    
    
    //判断状态
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_STATUS_URL_PATH,(model ? model.UserID : @""),[_dateDic objectForKey:@"ID"],[_dateDic objectForKey:@"UserID"]] view:nil success:^(id json) {
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            
            [_bottomView setDataDic:json];
            
            //点赞
            NSString *praiseStatus = json[@"PraiseStatus"];
            if ([praiseStatus intValue] == 1) {
                _bottomView.isParise = YES;
            } else {
                _bottomView.isParise = NO;
            }
            
            NSString *CollectStatus = json[@"CollectStatus"];
            if ([CollectStatus intValue] == 1) {
                _bottomView.isCollect = YES;
            } else {
                _bottomView.isCollect = NO;
            }
            
            [_tableView reloadData];
        }
        
        
    } failure:^(NSError *error) {

    }];
    
    
    //value
    NSString *CoverPath = [_dateDic objectForKey:@"CoverPath"];
    if (![CoverPath isKindOfClass:[NSNull class]]) {
        noLrcView.hidden = YES;
        [_bgImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,CoverPath]] placeholderImage:[UIImage imageNamed:@"qinzixiubofangqi_moren"] options:SDWebImageRetryFailed];
    } else {
        noLrcView.hidden = NO;
    }
    
    NSString *faceImg = [_dateDic objectForKey:@"FaceImg"];
    if (![faceImg isKindOfClass:[NSNull class]]) {
        [_userImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,faceImg]] placeholderImage:[UIImage imageNamed:@"story_header_bg"] options:SDWebImageRetryFailed];
    } else {
        _userImgView.image = [UIImage imageNamed:@"story_header_bg"];
    }
    _nickNameLb.text = [_dateDic objectForKey:@"NickName"];
    if ([_dateDic.allKeys containsObject:@"UserID"]) {
        if ([model.UserID intValue] == [[_dateDic objectForKey:@"UserID"]intValue]) {
            _nickNameLb.text = [NSString stringWithFormat:@"%@",model.NickName];
            NSString *faceImg = model.FaceImg;
            if (![faceImg isKindOfClass:[NSNull class]]) {
                [_userImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,faceImg]] placeholderImage:[UIImage imageNamed:@"story_header_bg"] options:SDWebImageRetryFailed];
            } else {
                _userImgView.image = [UIImage imageNamed:@"story_header_bg"];
            }
        }
    }
    
    _timeLb.text = [[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"CreateTime"]] getChaTime];

    _listenCount.text = [NSString stringWithFormat:@"试听次数%@次",[[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"AuditionNum"]] getValues]];
    float listenWidth = [_listenCount.text boundingRectWithSize:CGSizeMake(1000, _listenCount.height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:_listenCount.font} context:nil].size.width+4;
    _listenCount.width = listenWidth;
    _listenCount.right = SCREEN_WIDTH-25*PERCEN;
    listenImgView.right = _listenCount.left;
    
     _bottomView.dataDic = _dateDic;
    [_tableView reloadData];
    [self onLoadPraiseDB];
    
    //当前第几首歌以及类型播放器
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%d",(int)musicArrayNumber] forKey:@"music_list_CurrentNum"];
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%d",(int)2] forKey:@"music_Type_CurrentNum"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [self onAddMedia];
}

//评论接口
- (void)onShowCommentData:(UserModel *)model
{
    [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_SHOW_INFO_URL_PATH,[_dateDic objectForKey:@"ID"],[_dateDic objectForKey:@"UserID"],(model ? model.UserID : @""),@1] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        
        [_mutArr removeAllObjects];
        [_mutHeightArr removeAllObjects];
        
        if ([json[@"ret_code"] integerValue]==0) {
            NSArray *arr = json[@"data"];
            
            if ([arr isKindOfClass:[NSArray class]]) {
                //调整返回数据
                [self onSetUpReplyData:arr];
                
            }
        }
        
        //value
        fansNum = [NSString stringWithFormat:@"%@",json[@"FansNum"]];
        if ([fansNum isEqualToString:@"<null>"]) {
            fansNum = @"0";
        }
        _fansLb.text = [NSString stringWithFormat:@"%@个粉丝",fansNum];
        statusStr = [NSString stringWithFormat:@"%@",json[@"Status"]];
        if ([statusStr intValue] == 1) {
            _focusBtn.selected = YES;
        } else {
            _focusBtn.selected = NO;
        }
        
        _bottomView.commentNum = [NSString stringWithFormat:@"%@",json[@"CommentNum"]];
        [_tableView reloadData];
        
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
    }];
}

//锁屏显示
- (void)onAddMedia
{
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
        
        NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:_bgImgView.image];
        
        [ songInfo setObject:currentMusic.name forKey:MPMediaItemPropertyTitle ];
        [ songInfo setObject:[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"NickName"]] forKey:MPMediaItemPropertyArtist ];
        //        [ songInfo setObject: @"Audio Album" forKey:MPMediaItemPropertyAlbumTitle ];
        [ songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork ];
        //设置歌曲时长
        CMTime duration = audioPlayer.currentItem.duration;
        if (duration.timescale > 0) {
            double totalTime = (audioPlayer.currentItem.duration.value / audioPlayer.currentItem.duration.timescale);
            [songInfo setObject:[NSNumber numberWithDouble:totalTime] forKey:MPMediaItemPropertyPlaybackDuration];
        }
        //设置已经播放时长
        CMTime current = audioPlayer.currentItem.currentTime;
        if (current.timescale > 0) {
            double currentTime = (audioPlayer.currentItem.currentTime.value / audioPlayer.currentItem.currentTime.timescale);
            [songInfo setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        }
        
        [ [MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo ];
    }
}

//调整返回数据
- (void)onSetUpReplyData:(NSArray *)arr
{
    //数据调整
    for (NSDictionary *dictionary in arr) {
        NSArray *array = [dictionary objectForKey:@"ReplyInfo"];
        if ([array isKindOfClass:[NSArray class]]) {
            if (array.count > 0) {
                //存有回复内容,先存评论内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
                
                for (NSDictionary *dic in array) {
                    NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                    [mutDic setObject:dic forKey:@"ReplyInfo"];
                    [_mutArr addObject:mutDic];
                }
            } else {
                //没有回复内容
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
                [mutDic setObject:@{} forKey:@"ReplyInfo"];
                [_mutArr addObject:mutDic];
            }
        } else {
            //没有回复内容
            NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:dictionary];
            [mutDic setObject:@{} forKey:@"ReplyInfo"];
            [_mutArr addObject:mutDic];
        }
    }
    
    //高度获取
    [self onLoadDataForHeight];
}

 //高度获取
- (void)onLoadDataForHeight
{
    [_mutHeightArr removeAllObjects];
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];
    paragraph.lineSpacing = 6*PERCEN;
    
    for (NSDictionary *dic in _mutArr) {
        NSDictionary *ReplyInfo = [dic objectForKey:@"ReplyInfo"];
        CGFloat contentHiehgt = 0;
        if ([ReplyInfo isKindOfClass:[NSDictionary class]]) {
            if (ReplyInfo.allKeys.count == 0) {
                //评论
                NSString *content = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"Content"]] replaceUnicode];
                
                NSMutableAttributedString *mutAttributing = [[NSMutableAttributedString alloc]initWithString:content];
                [mutAttributing addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, content.length)];
                [mutAttributing addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.] range:NSMakeRange(0, content.length)];
                
                contentHiehgt = [mutAttributing boundingRectWithSize:CGSizeMake((ISIPAD?SCREEN_WIDTH-920*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):SCREEN_WIDTH-50*PERCEN), 1000) options:1|2 context:nil].size.height;
            } else {
                //回复
                //内容
                NSString *comment = [[NSString stringWithFormat:@"%@",[ReplyInfo objectForKey:@"ReplyCont"]] replaceUnicode];
                NSString *str1 = @"回复";
                NSString *str2 = [NSString stringWithFormat:@"%@",[ReplyInfo objectForKey:@"RepliedName"]];
                NSString *content = [NSString stringWithFormat:@"%@%@: %@",str1,str2,comment];
                
                NSMutableAttributedString *mutAttributing = [[NSMutableAttributedString alloc]initWithString:content];
                [mutAttributing addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, content.length)];
                [mutAttributing addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.] range:NSMakeRange(0, content.length)];
                
                contentHiehgt = [mutAttributing boundingRectWithSize:CGSizeMake((ISIPAD?SCREEN_WIDTH-920*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):SCREEN_WIDTH-50*PERCEN), 1000) options:1|2 context:nil].size.height;
            }
            
            //总高度
            contentHiehgt = 20*PERCEN+40+12*PERCEN+contentHiehgt+5;
            [_mutHeightArr addObject:[NSNumber numberWithFloat:contentHiehgt]];
        }
    }
}

- (void)onLoadPraiseDB
{
    //加载点赞列表
    NSArray *praiseDBArr = [UserManager standerDefult].praiseListArr;
    [_praiseListArr removeAllObjects];
    BOOL isParise = NO;
    if (praiseDBArr.count > 0) {
        for (NSDictionary *praiseDic in praiseDBArr) {
            NSString *praiseType = [praiseDic objectForKey:@"PraisedType"];
            if ([praiseType intValue] == 1) {
                //亲子秀
                NSString *idStr = [NSString stringWithFormat:@"%@",[praiseDic objectForKey:@"PraisedID"] ];
                NSDictionary *nDic = @{@"PraisedID":[NSString stringWithFormat:@"%@",idStr]};
                if ([[nDic objectForKey:@"PraisedID"] isEqualToString:[NSString stringWithFormat:@"%@",currentMusic.ID]]) {
                    isParise = YES;
                }
                [_praiseListArr addObject:nDic];
            }
        }
    }
    
    //收藏亲子秀
    NSArray *musicCollecion = [UserManager standerDefult].collectionShowArr;
    [collectionMusicArr removeAllObjects];
    BOOL isCollection = NO;
    if (musicCollecion.count > 0) {
        for (NSString *praiseType in musicCollecion) {
            //亲子秀
            if ([praiseType intValue] == [currentMusic.ID intValue]) {
                isCollection = YES;
            }
            [collectionMusicArr addObject:praiseType];
        }
    }

    
    if (_bottomView) {
        _bottomView.isParise = isParise;
        _bottomView.isCollect = isCollection;
    }
}

#pragma mark 载入歌曲数组
- (void)initDate {
    //获取音频列表的歌曲数据
    NSMutableArray *musicArr = [UserManager standerDefult].musicArr;
    if (musicArr.count > 0) {
        musicArray = [[NSMutableArray alloc]initWithArray:musicArr];
    }
    //
    musicArrayNumber = [UserManager standerDefult].selectMusicIndex;
    
    //获取当前的歌曲信息
    if (musicArray.count > musicArrayNumber) {
        currentMusic = musicArray[musicArrayNumber];
    }
    
    //亲子秀歌曲列表保存
    [NSKeyedArchiver archiveRootObject:musicArray toFile:[MusicCachesDirectory stringByAppendingPathComponent:@"collectionMusic.data"]];
    [NSKeyedArchiver archiveRootObject:_dataAllArr toFile:[MusicCachesDirectory stringByAppendingPathComponent:@"last_qinzixiu.data"]];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return (_mutArr.count > 5 ? 5 : _mutArr.count);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"News_Detail_Cell";
    MBSpaceNewsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceNewsDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.isFromShow=NO;
    }
    cell.orientation = self.orientation;
    
    if (_mutArr.count > indexPath.row ) {
        cell.dataDic = [_mutArr objectAtIndex:indexPath.row];
        cell.isShowUserNews = NO;
        
        NSString *taUserId = [_dateDic objectForKey:@"UserID"];
        if ([taUserId isKindOfClass:[NSNull class]]) {
            cell.zhuBoId = @"0";
        } else {
            cell.zhuBoId = taUserId;
        }
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mutHeightArr.count > indexPath.row ) {

        return [[_mutHeightArr objectAtIndex:indexPath.row]floatValue];
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    bgView.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(25*PERCEN, 0, 200, 30)];
    
    titleLb.backgroundColor = [UIColor clearColor];
    titleLb.textAlignment = NSTextAlignmentLeft;
    titleLb.textColor = UIColorFromHex(0x333333);
    titleLb.font = [UIFont systemFontOfSize:13.f];
    titleLb.text = [NSString stringWithFormat:@"评论  (%d)",(int)_mutArr.count];
    [bgView addSubview:titleLb];
    
    return bgView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark--点赞
- (void)onSelectItemPraiseWithView:(MBBottomView *)view withValue:(NSDictionary *)value    //点赞
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (![value isKindOfClass:[NSDictionary class]]) return;
    if (!model) return;
    
    //区分点赞或取消点赞
    NSString *idStr = [NSString stringWithFormat:@"%@",[value objectForKey:@"PraiseStatus"]];
    if ([idStr boolValue] == YES) {
        //取消点赞
        [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_CANCEL_ZAN_URL_PATH,model.UserID,[_dateDic objectForKey:@"ID"],@1] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //取消点赞成功
                [_bottomView onChangePraiseDate:NO];
                
                NSMutableDictionary *nDic = [[NSMutableDictionary alloc]initWithDictionary:value];
                [nDic setObject:@0 forKey:@"PraiseStatus"];
                [nDic setObject:[NSString stringWithFormat:@"%d",[[value objectForKey:@"PraiseNum"] intValue]-1] forKey:@"PraiseNum"];
                [_bottomView setDataDic:nDic];
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    } else  {
        //点赞
        [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_ZAN_URL_PATH,model.UserID,[_dateDic objectForKey:@"ID"],@1] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //点赞成功
                [_bottomView onChangePraiseDate:YES];
                NSMutableDictionary *nDic = [[NSMutableDictionary alloc]initWithDictionary:value];
                [nDic setObject:@1 forKey:@"PraiseStatus"];
                [nDic setObject:[NSString stringWithFormat:@"%d",[[value objectForKey:@"PraiseNum"] intValue]+1] forKey:@"PraiseNum"];
                [_bottomView setDataDic:nDic];
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    }

}
#pragma mark - 收藏
- (void)onselectItemForShouCangWithView:(MBBottomView *)view withValue:(NSDictionary *)value
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (![value isKindOfClass:[NSDictionary class]]) return;
    if (!model) return;
    
    //区分收藏和未收藏
    NSString *idStr = [NSString stringWithFormat:@"%@",[value objectForKey:@"CollectStatus"]];
    if ([idStr intValue] == YES) {
        //取消收藏
        [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_COLLECTION_REMOVE_URL_PATH,model.UserID,[_dateDic objectForKey:@"ID"],@3] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //取消点赞成功
                [_bottomView onChangeCollectionDate:NO];
                NSMutableDictionary *nDic = [[NSMutableDictionary alloc]initWithDictionary:value];
                [nDic setObject:@0 forKey:@"CollectStatus"];
                [nDic setObject:[NSString stringWithFormat:@"%d",[[value objectForKey:@"CollectNum"] intValue]-1] forKey:@"CollectNum"];
                [_bottomView setDataDic:nDic];
                
                //数据更新
                NSString *ids = [NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"ID"]];
                [collectionMusicArr removeObject:ids];
                [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collectionMusicArr];
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    } else  {
        //收藏
        [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_COLLECTION_COLLECION_URL_PATH,model.UserID,[_dateDic objectForKey:@"ID"],@3] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                //点赞成功
                [_bottomView onChangeCollectionDate:YES];
                NSMutableDictionary *nDic = [[NSMutableDictionary alloc]initWithDictionary:value];
                [nDic setObject:@1 forKey:@"CollectStatus"];
                [nDic setObject:[NSString stringWithFormat:@"%d",[[value objectForKey:@"CollectNum"] intValue]+1] forKey:@"CollectNum"];
                [_bottomView setDataDic:nDic];
                
                //数据更新
                NSString *ids = [NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"ID"]];
                [collectionMusicArr addObject:ids];
                [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collectionMusicArr];
                
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                if ([UserManager standerDefult].isLoadMusic == YES && app.networkStatus == ReachableViaWiFi) {
                    [self onSelectdownload];
                }
                
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    }

}

#pragma mark -评论
- (void)onSelectITemForCommentWithView:(MBBottomView *)view
{
    //评论
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        isZheDang = YES;
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }

    //响应键盘
    if (_inputField) {
        _emojiView.alpha = 0;
        emojiBt.selected = NO;
        [_inputField becomeFirstResponder];
    }
    
}

#pragma mark - 回复
- (void)onSelectControlForReplyWithValue:(NSDictionary *)value withView:(MBSpaceNewsDetailCell *)view
{
    //回复
    if ([value isKindOfClass:[NSDictionary class]]) {
        [_replyMutDic removeAllObjects];
        [_replyMutDic addEntriesFromDictionary:value];
    }
    
    //响应键盘
    if (_inputField) {
        _emojiView.alpha = 0;
        emojiBt.selected = NO;
        [_inputField becomeFirstResponder];
    }
}

#pragma mark - emoji
- (void)onSelectEmojiAction:(UIButton *)bt
{
    if (bt.selected == NO) {
        _emojiView.alpha = 1.f;
        [_inputField resignFirstResponder];
    } else {
        _emojiView.alpha = 0.f;
        [_inputField becomeFirstResponder];
    }
    
    //    bt.selected = !bt.selected;
}

#pragma mark -发送
- (void)onSelectSureAction
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (_inputField.text.length == 0) {
        return;
    }
    if (!model)return;
    
    [self onTapHideInputAction];
    
    if (_replyMutDic.allKeys.count > 0) {
        //有值，表示是回复
        NSString *text = _inputField.text;
        
        NSString *uniStr = [NSString stringWithUTF8String:[text UTF8String]];
        NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
        NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
        
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_REPLY_INFO_URL_PATH,model.UserID,[_replyMutDic objectForKey:@"ID"],[_replyMutDic objectForKey:@"UserID"],goodStr] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                
                NSDate *date = [NSDate date];
                
                NSDictionary *nDic = @{@"ComID":[_replyMutDic objectForKey:@"ID"],
                                       @"CreateTime":[NSString stringWithFormat:@"%.f",[date timeIntervalSince1970]],
                                       @"ID":@"1",
                                       @"RepliedName":[_replyMutDic objectForKey:@"NickName"],
                                       @"ReplyCont":_inputField.text,
                                       @"ReplyName":model.NickName,
                                       @"ReplyImg":model.FaceImg,
                                       @"ToUserID":[_replyMutDic objectForKey:@"UserID"],
                                       @"UserID":model.UserID};
                NSMutableDictionary *mutDic = [[NSMutableDictionary alloc]initWithDictionary:_replyMutDic];
                [mutDic setValue:nDic forKey:@"ReplyInfo"];
                int indexDic = (int)[_mutArr indexOfObject:_replyMutDic];
                //从选中的楼层中插入数据，数据显示在回复最底层
                indexDic = [self getReplyCengByData:(indexDic+1)];
                
                if (indexDic <= _mutArr.count && indexDic >= 0) {
                    [_mutArr insertObject:mutDic atIndex:indexDic];
                    _inputField.text = @"";
                    //高度自定义
                    [self onLoadDataForHeight];
                    
                    [_tableView reloadData];
                } else {
                    [self onShowCommentData:model];
                }
                [_replyMutDic removeAllObjects];
                _inputField.text = @"";
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    } else { //评论
        NSString *text = _inputField.text;
        
        NSString *uniStr = [NSString stringWithUTF8String:[text UTF8String]];
        NSData *uniData = [uniStr dataUsingEncoding:NSNonLossyASCIIStringEncoding];
        NSString *goodStr = [[NSString alloc] initWithData:uniData encoding:NSUTF8StringEncoding] ;
        

        
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FORUM_COMMENT_INFO_URL_PATH,model.UserID,[_dateDic objectForKey:@"UserID"],[_dateDic objectForKey:@"ID"],goodStr,@1,@""] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                _inputField.text = @"";
                [self onLoadData];
            } else {
                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    }
}

//从选中的楼层中插入数据，数据显示在回复最底层
- (int)getReplyCengByData:(int)selectIndex
{
    if (selectIndex < _mutArr.count && selectIndex >= 0) {
        for (int i = selectIndex;i < _mutArr.count; i++) {
            NSDictionary *dictionary = [_mutArr objectAtIndex:i];
            NSDictionary *dic = [dictionary objectForKey:@"ReplyInfo"];
            if ([dic isKindOfClass:[NSDictionary class]]) {
                if (dic.allKeys.count == 0) {
                    return i;
                }
            }
        }
        
        return (int)_mutArr.count;
    }
    else if (selectIndex == _mutArr.count+1) {
        //最后一个没有回复的评论
        return selectIndex;
    }
    return -1;
}

#pragma mark - 查看所有评论
- (void)onSelectForNewCellAction
{
    //查看所有评论
    MBSpaceNewsDetailViewController *com = [[MBSpaceNewsDetailViewController alloc] init];
    com.dataArr = _mutArr;
    com.isFormMyNews = NO;
    com.taUserID = [NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"UserID"]];
    [self.navigationController pushViewController:com animated:YES];
    
}

#pragma mark -分享
-(void)onSelectITemForShareWithView:(MBBottomView *)view withValue:(NSDictionary *)value{
    
    if (![value isKindOfClass:[NSDictionary class]]) return;
    if (value.allKeys.count > 0) {
        [shareView setShareVC:self content:[NSString stringWithFormat:@"分享:%@",currentMusic.name] image:[UIImage imageNamed:@"logo_dl_29"] url:[NSString stringWithFormat:SHARE_SHOW_URL_PATH,currentMusic.ID]];
        [shareView addAudioId:[NSString stringWithFormat:@"%@",currentMusic.ID] withType:@3];
        [shareView show];
        
        //分享数据更新
        if (_dateDic.allKeys.count > 0) {
            if ([_dataAllArr containsObject:_dateDic]) {
                int index = (int)[_dataAllArr indexOfObject:_dateDic];
                NSMutableDictionary *nMutArr = [[NSMutableDictionary alloc]initWithDictionary:_dateDic];
                [nMutArr setObject:[NSNumber numberWithInt:([[_dateDic objectForKey:@"ShareNum"] intValue]+1)] forKey:@"ShareNum"];
                [_dataAllArr replaceObjectAtIndex:index withObject:nMutArr];
                _bottomView.shareNum = [NSString stringWithFormat:@"%@",[nMutArr objectForKey:@"ShareNum"]];
            }
        }
    }
}

#pragma mark - 键盘相关
- (void)registerForKeyboardNotifications
{
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShow:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
}

- (void)removeForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    float keyboardhight = 0;
    if(kbSize.height == 216)
    {
        keyboardhight = 0;
    }
    else
    {
        keyboardhight = kbSize.height-216;   //258 - 216 系统键盘的两个不同高度
    }
    //输入框位置动画加载
    inputTime = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    _emojiView.alpha = 0;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:NO WithHeight:keyboardhight WithDuration:inputTime];
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //do something
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
    
    //释放
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

//输入框和遮挡层动画效果
- (void)onAnimationWithInputView:(BOOL)isHidden WithHeight:(float)heght WithDuration:(float)time
{
    if (isZheDang ) {
        return;
    }
    [UIView animateWithDuration:time animations:^{ 
        
        if (_emojiView.alpha == 0) {
            emojiBt.selected = NO;
            _emojiView.top = SCREEN_WIDTH;
            _inputView.top = (isHidden == YES ? SCREEN_HEIGHT : SCREEN_HEIGHT-216-heght-40);
            _inputView.hidden = isHidden;
            _showderView.hidden = isHidden;
            _showderView.height = _inputView.top;
        } else {
            emojiBt.selected = YES;
            _emojiView.top = SCREEN_HEIGHT - 216;
            _inputView.top = _emojiView.top-40;
            _inputView.hidden = NO;
            _showderView.height = _inputView.top;
            _showderView.hidden = NO;
        }
        
    } completion:^(BOOL finished) {
        if (finished) {
          //  _inputField.text = @"";
        }
    }];
}

- (void)onTapHideInputAction
{
    [_inputField resignFirstResponder];
    _emojiView.alpha = 0 ;
    emojiBt.selected = NO;
    [self onAnimationWithInputView:YES WithHeight:0 WithDuration:inputTime];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int lengthCount = (int)(textField.text.length + string.length);
    if (lengthCount >= 101) {
        return NO;
    }
    return YES;
}

#pragma mark -Action

- (void)onBack {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -删除
- (void)onDeleteMusicAction {

    [audioPlayer pause];
    [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_SHOWDELETE_URL_PATH,currentMusic.ID,[_dateDic objectForKey:@"UserID"]] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        
        if ([json[@"ret_code"] intValue] == 0) {
            [ErrorMessage showErrorMessage:json[@"message"] inView:_scrollView];
            //清除数据
            if (musicArray.count > musicArrayNumber) {
               
                [musicArray removeObjectAtIndex:musicArrayNumber];
                [_dataAllArr removeObjectAtIndex:musicArrayNumber];
                [[UserManager standerDefult].musicArr removeAllObjects];
                [[UserManager standerDefult].musicArr addObjectsFromArray:musicArray];
                
                if (musicArray.count <= musicArrayNumber) {
                    //当是最后一个
                    if (musicArray.count == 0) {
                        [self back];
                         [[UserManager standerDefult] setMainPlayer:nil];
                        return ;
                    } else {
                        musicArrayNumber = musicArray.count-1;
                    }
                }
                
                if (musicArray.count > musicArrayNumber) {
                    currentMusic = [musicArray objectAtIndex:musicArrayNumber];
                    [self updatePlayerSetting];
                }
                
            }
        } else {
            [ErrorMessage showErrorMessage:@"删除失败" inView:_scrollView];
            if (playBt.selected == YES) {
                [audioPlayer play];
            }
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        if (playBt.selected == YES) {
            [audioPlayer play];
        }
    }];
}

#pragma mark -播放
- (void)onSelectPlayedType:(UIButton *)bt {
    bt.selected = !bt.selected;
    if (bt.selected) {
        [audioPlayer play];
        
        isPlay = YES;
        if (!_showTimer) {
            //设置监控 每秒刷新一次时间
            _showTimer =[NSTimer scheduledTimerWithTimeInterval:0.1f
                                                         target:self
                                                       selector:@selector(showTime)
                                                       userInfo:nil
                                                        repeats:YES];
        }
        //试听次数
        [self addAudioNumAction];
    } else {
        [audioPlayer pause];
       
        isPlay = NO;
        if (_showTimer) {
            [_showTimer invalidate];
            _showTimer = nil;
        }
    }

}

- (void)showTime
{
    //动态更新进度条时间
    int currentTime = 0;
    int durationTime = 0;
    if (audioPlayer.currentItem.currentTime.timescale != 0) {
        currentTime = (int)(audioPlayer.currentItem.currentTime.value / audioPlayer.currentItem.currentTime.timescale);
    }
    if (audioPlayer.currentItem.duration.timescale != 0) {
        durationTime = (int) (audioPlayer.currentItem.duration.value / audioPlayer.currentItem.duration.timescale);
    }
    slide.value = 1.0 * currentTime / durationTime;
    if (slide.value == 0) {
        ++nextPlay;
        if (nextPlay == 8) {
//            [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
        }
        if (nextPlay == 60*2) {
//            [audioPlayer replaceCurrentItemWithPlayerItem:nil];
            [self autoPlay];
            nextPlay = 1;
            [audioPlayer play];
            return;
        }
    } else {
        [MBProgressHUD hideAllHUDsForView:_scrollView animated:YES];
        nextPlay = 1;
    }
    
    //如果播放完，调用自动播放下一首
    if (slide.value > 0.999) {
        [self autoPlay];
    }
}

- (void)movieToEnd:(NSNotification*)noty
{
    if (audioPlayer && [UserManager standerDefult].isBackPlay == NO) {
        AVPlayerItem *currentItem = noty.object;
        if ([audioPlayer.currentItem isEqual:currentItem]) {
            [self autoPlay];
        }
    }
}

- (void)movieToFaile:(NSNotification *)noty
{
    if (audioPlayer && [UserManager standerDefult].isBackPlay == NO) {
        AVPlayerItem *currentItem = noty.object;
        if ([audioPlayer.currentItem isEqual:currentItem]) {
            [self autoPlay];
        }
    }
}

#pragma mark - 上传试听次数
- (void)addAudioNumAction
{
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_AUDIONUM_URL_PATH,[_dateDic objectForKey:@"ID"],@2] view:nil success:^(id json) {

        if ([json[@"ret_code"] integerValue]==0) {
            NSMutableDictionary *mutDics = [[NSMutableDictionary alloc]initWithDictionary:_dateDic];
            int praiseNu = [[mutDics objectForKey:@"AuditionNum"] intValue]+1;
            praiseNu = praiseNu >= 0 ? praiseNu : 0;
            [mutDics setValue:[NSString stringWithFormat:@"%d",praiseNu] forKey:@"AuditionNum"];
            if (musicArrayNumber < _dataAllArr.count) {
                [_dataAllArr replaceObjectAtIndex:(int)musicArrayNumber withObject:mutDics];
                [_dateDic removeAllObjects];
                [_dateDic addEntriesFromDictionary:mutDics];
            }
            [_tableView reloadData];
        }

        
    } failure:^(NSError *error) {
       
    }];
}

#pragma mark -单曲循环
- (void)singleCircle {
    NSLog(@"单曲循环");
    if (playModelType == PLayerModelType_Shunxu) {
        playModelType = PLayerModelType_SuiJi;
        
        [singleBtn setImage:[UIImage imageNamed:@"suiji"] forState:UIControlStateNormal];
        [singleBtn setImage:[UIImage imageNamed:@"suiji"] forState:UIControlStateHighlighted];
        [[NSUserDefaults standardUserDefaults]setObject:@"2" forKey:@"qinzixiu_play_Type"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    else  if (playModelType == PLayerModelType_SuiJi) {
        playModelType = PLayerModelType_DanQu;
        
        [singleBtn setImage:[UIImage imageNamed:@"danqu"] forState:UIControlStateNormal];
        [singleBtn setImage:[UIImage imageNamed:@"danqu"] forState:UIControlStateHighlighted];
        [[NSUserDefaults standardUserDefaults]setObject:@"3" forKey:@"qinzixiu_play_Type"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    else  if (playModelType == PLayerModelType_DanQu) {
        playModelType = PLayerModelType_Shunxu;
        
        [singleBtn setImage:[UIImage imageNamed:@"shunxu"] forState:UIControlStateNormal];
        [singleBtn setImage:[UIImage imageNamed:@"shunxu"] forState:UIControlStateHighlighted];
        [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"qinzixiu_play_Type"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    
}

//改变进度条
- (void)onChangeSlide
{
    CGFloat duration = audioPlayer.currentItem.duration.value / audioPlayer.currentItem.duration.timescale;
    NSInteger dragedSeconds = floorf(duration*slide.value);
    
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
    
    [audioPlayer pause];
    [_showTimer invalidate];
    _showTimer = nil;
    [audioPlayer seekToTime:dragedCMTime completionHandler:^(BOOL finish){
        if (finish) {
            if (!_showTimer) {
                //设置监控 每秒刷新一次时间
                _showTimer =[NSTimer scheduledTimerWithTimeInterval:0.1f
                                                             target:self
                                                           selector:@selector(showTime)
                                                           userInfo:nil
                                                            repeats:YES];
            }
            [audioPlayer play];
        }
        
    }];

}

#pragma mark - 上一曲
- (void)onSelectLastPlaying {
    NSLog(@"上一曲");
    if (playModelType == PLayerModelType_Shunxu) {
        //顺序
        if (musicArrayNumber == 0) {
            musicArrayNumber = musicArray.count;
        }
        musicArrayNumber --;
    }
    else if (playModelType == PLayerModelType_SuiJi) {
        musicArrayNumber = arc4random()%(musicArray.count);
    }
    else if (playModelType == PLayerModelType_DanQu) {
        
    }
    
    [self updatePlayerSetting];
}

#pragma mark - 下一曲
- (void)onSelectNextPlaying {
    NSLog(@"下一曲");
    if (playModelType == PLayerModelType_Shunxu) {
        //顺序
        if (musicArrayNumber == musicArray.count - 1) {
            musicArrayNumber = -1;
        }
        musicArrayNumber ++;
    }
    else if (playModelType == PLayerModelType_SuiJi) {
        musicArrayNumber = arc4random()%(musicArray.count);
    }
    else if (playModelType == PLayerModelType_DanQu) {
        
    }
    
    [self updatePlayerSetting];
}

//更新播放器设置
- (void)updatePlayerSetting {
    
    if (musicArray.count <= musicArrayNumber) {
        return;
    }
    
    [[UserManager standerDefult]setSelectMusicIndex:musicArrayNumber];
    [self setTitleView:[musicArray[musicArrayNumber] name]];
    currentMusic = musicArray[musicArrayNumber];
    
    [self onLoadData];
    
    isPlay = YES;
    
    //更新曲目
    [audioPlayer pause];
    titleBgLb.text = [musicArray[musicArrayNumber] name];
    
    NSURL *urlPath;
    if (currentMusic.isCacheData) {
        NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",currentMusic.name,currentMusic.type]];
        urlPath = [NSURL fileURLWithPath:filePath];
    } else {
        urlPath = [NSURL URLWithString:currentMusic.urlPath];
    }
    
    AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];

    [audioPlayer replaceCurrentItemWithPlayerItem:item];
    
    if (playBt.selected == YES) {
        [audioPlayer play];
    } else {
        [audioPlayer pause];
    }
    
    //试听次数
    [self addAudioNumAction];
}

#pragma mark 自动进入下一首
- (void)autoPlay {
    if (playModelType == PLayerModelType_Shunxu) {
        //顺序
        if (musicArrayNumber == musicArray.count - 1) {
            musicArrayNumber = -1;
        }
        musicArrayNumber ++;
    }
    else if (playModelType == PLayerModelType_SuiJi) {
        musicArrayNumber = arc4random()%(musicArray.count);
    }
    else if (playModelType == PLayerModelType_DanQu) {
        
    }
    
    [self updatePlayerSetting];
}

#pragma mark - 下载
- (void)onSelectdownload {
    NSLog(@"下载");

    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }

    
    if (downloadBt.selected == YES) {
        //已下载
        return;
    }
    
    downloadBt.enabled = NO;
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:date];
    
    [[DownManager staredInstance]downloadWithUrl:currentMusic.urlPath
                                   withMusicName:[NSString stringWithFormat:@"%@.%@",currentMusic.name,currentMusic.type]
                                      withUserID:[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"UserID"]]
                                     withMusicID:currentMusic.ID
                                     withContent:currentMusic.Sentiment
                                   withMusicType:[NSString stringWithFormat:@"%@",currentMusic.musicType]
                                      withPicUrl:currentMusic.CoverPath
                                        withDate:dateString
                                     withUserPic:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_dateDic objectForKey:@"FaceImg"]]
                                    withUserNick:[NSString stringWithFormat:@"%@",[_dateDic objectForKey:@"NickName"]]
                                        withSize:[NSString stringWithFormat:@"%@",currentMusic.Capacity]
                                    withProgress:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
                                        
                                    } withStats:^(DownMusicState stats) {
                                        
                                    }];
    [ErrorMessage showErrorMessage:@"开始下载" inView:self.view];
    
    //下载次数接口
    [MBProgressHUD showHUDAddedTo:_scrollView animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_DOWN_LOADNUM_URL_PATH,model.UserID,currentMusic.ID,@2] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
   
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:_scrollView animated:YES];
    }];
}

#pragma mark -关注
- (void)focusClick:(UIButton *)btn {
    
    if (!_dateDic) {
        return;
    }
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model.UserID) {
        MBLoginController *registerLastVC = [[MBLoginController alloc] init];
        registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
        [self.navigationController pushViewController:registerLastVC animated:YES];
        return;
    }
    
    if (btn.selected == NO) {
        //关注
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_MYATTENTION_ADD_URL_PATH,[_dateDic objectForKey:@"UserID"],model.UserID] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                btn.selected = !btn.selected;
            }
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];
    } else {
        //取消关注
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_MYATTENTION_CANCEL_URL_PATH,[_dateDic objectForKey:@"UserID"],model.UserID] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                btn.selected = !btn.selected;
            }
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:_scrollView animated:YES];
        }];

    }
    
   
}

#pragma mark -远程控制
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [audioPlayer pause];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self onSelectNextPlaying];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self onSelectLastPlaying];
                break;
            case UIEventSubtypeRemoteControlPause:
                
                [audioPlayer pause];
                break;
            case UIEventSubtypeRemoteControlPlay:
                [audioPlayer play];
                break;
            default:
                break;
        }
    }
}

#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float y = scrollView.contentOffset.y;
    //    NSLog(@"滑动位移:%.2f",y);
    if (y > 0 && y < 276*PERCEN*2) {
        //变深色
        _navBgView.backgroundColor = [UIColorFromHex(0x333333)colorWithAlphaComponent:.35];
    }
    else if ((y <= 0 && y > -276*PERCEN)) {
        //变淡
        _navBgView.backgroundColor = [UIColorFromHex(0x333333)colorWithAlphaComponent:.0];
    }
}

#pragma mark - Emoji
- (void)onSelectItemForEmojiView:(NSString *)emoji withView:(EmojiView *)view
{
    if ([emoji isKindOfClass:[NSString class]]) {
        if (emoji.length > 0) {
            _inputField.text = [NSString stringWithFormat:@"%@%@",_inputField.text,emoji];
        }
    }
}

@end
